package com.friend.controller;

import com.friend.entity.LoginDTO;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Map;

/**
 * <p></p>
 *
 * @author jiuhua.xu
 * @version 1.0
 * @since JDK 1.8
 */
@RestController
public class TokenController {


    private final RestTemplate restTemplate;
//    private final static String TOKEN_URL = "http://localhost:8022/oauth/token";
    private final static String TOKEN_URL = "http://localhost:8081/auth/oauth/token";

    public TokenController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("token")
    public ResponseEntity<Object> tokenFromCode(String code) {

        //Http Basic 验证
//        String clientAndSecret = oAuth2ClientProperties.getClientId()+":"+oAuth2ClientProperties.getClientSecret();
//        String clientAndSecret = "clientId"+":"+"secret";
        //这里需要注意为 Basic 而非 Bearer
//        clientAndSecret = "Basic "+ Base64.getEncoder().encodeToString(clientAndSecret.getBytes());

        HttpHeaders httpHeaders = new HttpHeaders();
        //授权请求信息
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("grant_type", "authorization_code");
        map.add("code", code);
        map.add("redirect_uri", "http://localhost:8019/");
        map.add("scope", "all");
        //HttpEntity
        HttpEntity httpEntity = new HttpEntity(map, httpHeaders);
        //获取 Token
        ResponseEntity<Map> exchange = restTemplate.exchange(TOKEN_URL, HttpMethod.POST, httpEntity, Map.class);

        Map bodyMap = exchange.getBody();

        return ResponseEntity.ok(bodyMap);
    }

    @GetMapping("token/password")
    public ResponseEntity<Object> tokenFromPassword(@RequestBody LoginDTO loginDTO) {

        HttpHeaders httpHeaders = new HttpHeaders();
        //授权请求信息
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("username", loginDTO.getUsername());
        map.add("password", loginDTO.getPassword());
        map.add("grant_type", "password");
        map.add("scope", "all");
        //HttpEntity
        HttpEntity httpEntity = new HttpEntity(map, httpHeaders);
        //获取 Token
        ResponseEntity<Map> exchange = restTemplate.exchange(TOKEN_URL, HttpMethod.POST, httpEntity, Map.class);
        Map bodyMap = exchange.getBody();
        return ResponseEntity.ok(bodyMap);
    }

    @GetMapping("applyToken")
    public ResponseEntity<Object> applyToken(@RequestBody LoginDTO loginDTO)  {
        System.out.println(123);

        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String,  String> body  = new LinkedMultiValueMap<>();
        body.add("grant_type","password");
        body.add("username",loginDTO.getUsername());
        body.add("password",loginDTO.getPassword());
        HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(body, headers);
//        设置restTemplate远程调用时候，对400和401不让报错，正确返回数据
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if(response.getRawStatusCode()!=400 && response.getRawStatusCode()!=401){
                    super.handleError(response);
                }
            }
        });
//         远程调用申请令牌
        ResponseEntity<Map> exchange = restTemplate.exchange(TOKEN_URL, HttpMethod.POST, httpEntity, Map.class);
        Map bodyMap = exchange.getBody();
        return ResponseEntity.ok(bodyMap);
    }

    @GetMapping("findToken")
    public ResponseEntity<Object> findToken(@RequestBody LoginDTO loginDTO)  {

        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String,  String> body  = new LinkedMultiValueMap<>();
//        body.add("grant_type","password");
//        body.add("username",loginDTO.getUsername());
//        body.add("password",loginDTO.getPassword());
        HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(body, headers);
//        设置restTemplate远程调用时候，对400和401不让报错，正确返回数据
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
                if(response.getRawStatusCode()!=400 && response.getRawStatusCode()!=401){
                    super.handleError(response);
                }
            }
        });
//         远程调用申请令牌
        ResponseEntity<Map> exchange = restTemplate.exchange("http://localhost:8022/jdbc/token/find/admin", HttpMethod.GET, httpEntity, Map.class);
        Map bodyMap = exchange.getBody();
        return ResponseEntity.ok(bodyMap);
    }
}
